package org.easy.core.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;


public class UrlUtil {


    public static String encode(String str) {
        try {
            return URLEncoder.encode(str, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String decode(String str) {
        try {
            return URLDecoder.decode(str, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String fillHttp(String url) {
        if (url.startsWith("http://") || url.startsWith("https://")) {
            return url;
        }
        return "http://" + url;
    }

    public static List<String> fillHttp(List<String> urls) {
        return urls.stream().map(UrlUtil::fillHttp).collect(Collectors.toList());
    }


    public static String adapterToUrlPath(String url) {
        return url.replace("\\", "/");
    }

    public static Map<String, String> extractUrlParams(String url) {
        Map<String, String> map = new HashMap<>();
        url = url.replace("?", ";");
        if (!url.contains(";")) {
            return map;
        }
        if (url.split(";").length > 0) {
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr) {
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key, value);
            }
            return map;
        } else {
            return map;
        }
    }

    public static String buildUrlParams(String baseUrl, Map<String, String> map) {
        return baseUrl + "?" + getKeyString(map);
    }

    public static String getKeyString(Map<String, String> map) {
        StringBuffer stringUrl = new StringBuffer();
        //key 排序map
        Map<String, String> sortMap = sortMapByKey(map);
        //循环便利拼接关键key
        Set<Map.Entry<String, String>> entries = sortMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            stringUrl.append(entry.getKey() + "=" + entry.getValue() + "&");
        }
        String keyString = stringUrl.substring(0, stringUrl.length() - 1);
        return keyString;
    }

    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (o1).compareTo(o2);
            }
        });
        sortMap.putAll(map);
        return sortMap;
    }

    /**
     * 从url获取容器
     *
     * @param url url
     * @return {@link String}
     */
    public static String getContainerFromUrl(String url) {
        String tmp = url;
        if (url.contains("?")) {
            tmp = url.substring(0, url.indexOf("?"));
        }

        return tmp.substring(tmp.lastIndexOf(".") + 1);
    }
}
